package com.zhome.gateway.filter.pre;

import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zhome.gateway.constants.Constants;
import com.zhome.gateway.dto.ZhomeRouteDto;
import com.zhome.gateway.enums.FilterEnum;
import com.zhome.gateway.enums.GateWayCodeEnum;
import com.zhome.gateway.filter.AbstractZhomeZuulFilter;
import com.zhome.gateway.util.DesEncrypt;
import lombok.extern.slf4j.Slf4j;

/**
 * 进行Mock操作的过滤器
 * @author cuiyh9
 * @date 2020/5/9
 */
@Slf4j
public class MockFilter extends AbstractZhomeZuulFilter {
    @Override
    public String filterType() {
        return Constants.PRE_KEY;
    }

    @Override
    public int filterOrder() {
        return FilterEnum.MockFilterEnum.getFilterOrder();
    }

    @Override
    public boolean shouldFilter() {
        RequestContext ctx = RequestContext.getCurrentContext();
        return ctx.getBoolean(Constants.RequestContextKey.CTX_X_SUCCESSOR_CAN_EXECUTE);
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext ctx = RequestContext.getCurrentContext();
        if (ctx.getBoolean(Constants.RequestContextKey.CTX_X_IS_MOCK)) {
            setSkipToPostTypeFilter(ctx);
            mockResponse(ctx);
        } else {
            setSkipNextFilter(ctx);
        }
        return null;
    }

    /**
     *
     * @param ctx
     */
    public void mockResponse(RequestContext ctx) {
        ZhomeRouteDto zhomeRouteDto = (ZhomeRouteDto)ctx.get(Constants.RequestContextKey.CTX_X_ROUTEINFO);
        String message = gatewayResponseEncrypt(GateWayCodeEnum.CODE_SUCCESS, zhomeRouteDto.getMockValue());
        ctx.setResponseBody(message);
        ctx.addZuulResponseHeader(Constants.RequestHeader.CONTENT_TYPE, Constants.APPLICATION_JSON);
        ctx.setSendZuulResponse(true);
        ctx.setRouteHost(null);

    }

}
